import pandas as pd
import sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score
 
class ClusterUtils(object):
    def __init__(self):
        self.df = pd.read_csv('./scenic_data.csv')

    def get_k(self):
        features = self.df[['non_weekend', 'out_province_ratio', 'elderly_ratio']]
        scaler = StandardScaler()
        scaler_features = scaler.fit_transform(features)

        kmeans = KMeans(n_clusters = 4, random_state=42)
        self.df['cluster'] = kmeans.fit_predict(scaler_features)

        print(self.df[['tourist_agency_name', 'cluster']])

        centers = scaler.inverse_transform(kmeans.cluster_centers_)
        print(pd.DataFrame(centers, columns=['non_weekend', 'out_province_ratio', 'elderly_radio']))

        self.df.to_csv('clustered_agencies.csv', index=False)

        centers_df = pd.DataFrame(centers, columns=features.columns)
        centers_df['cluster'] = [f'Cluster {i}' for i in range(centers.shape[0])]

        centers_long = centers_df.melt(id_vars='cluster', var_name='freture', value_name='value')

        colors = ['#1f77b4', '#ff7f0e', '#2ca02c']
        plt.figure(figsize=(10, 6))
        sns.barplot(x='feature', y = 'value', hue ='cluster', data = centers_long, palette=colors)

        plt.rcParams['font.sans-serif'] = ['SimHer']
        plt.rcParams['axes.unicode_minus'] = False
        plt.title('聚类中心特征对比')
        plt.ylabel('比例')
        plt.ylim(0, 1)
        plt.legend(title='簇', bbox_to_anchor=(1.05, 1), loc='upper left')

        for p in plt.gca().patches:
            height = p.get_height()
            plt.gca().text(p.get_x() + p.get_width() / 2, height + 0.02,
                           f'{height: .2f}',ha='center')
        plt.tight_layout()
        plt.show()


if __name__ == '__main__':
    cu = ClusterUtils()
    cu.get_k()